/*
 * BanBu_ChangePWViewController
 * @description 本文件提供系统设置修改密码界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供系统设置修改密码界面的ViewController
 */

#import "BanBu_ChangePWViewController.h"
#import "TKLoadingView.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "BanBu_ThemeManager.h"
#import "UIViewController+Animation.h"

@interface BanBu_ChangePWViewController ()

@end

@implementation BanBu_ChangePWViewController

- (id)init
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.title = NSLocalizedString(@"changePWTitle", nil);
    BanBu_NavButton *cancel = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
    cancel.position = ButtonPositionLeft;
    //    cancel.frame=CGRectMake(0, 0,40, 30);
    [cancel addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    //    [cancel setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    //    [cancel setTitle:NSLocalizedString(@"returnButton", nil) forState:UIControlStateNormal];
    //    cancel.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *cancelItem = [[[UIBarButtonItem alloc] initWithCustomView:cancel] autorelease];
    self.navigationItem.leftBarButtonItem = cancelItem;
    [cancel release];
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];
    self.tableView.backgroundView = img;
    
    BanBu_NavButton *save = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    save.frame=CGRectMake(0, 0, 50, 30);
    save.position = ButtonPositionRight;
    [save addTarget:self action:@selector(complete:) forControlEvents:UIControlEventTouchUpInside];
    [save setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    save.titleLabel.font = [UIFont systemFontOfSize:16];
    [save setTitle:NSLocalizedString(@"saveButton", nil) forState:UIControlStateNormal];
    //    save.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *saveItem = [[[UIBarButtonItem alloc] initWithCustomView:save] autorelease];
    self.navigationItem.rightBarButtonItem = saveItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)cancel:(UIButton *)button
{
    //    [self dismissViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)complete:(UIButton *)button
{
    NSString *errorMsg = nil;
    
    if(!_oldPWField.text.length)
    {
        errorMsg = NSLocalizedString(@"errorMsg6", nil);
    }
    else if(!_newPWField.text.length)
    {
        errorMsg = NSLocalizedString(@"errorMsg7", nil);
    }
    else if(_newPWField.text.length<6)
    {
        errorMsg = NSLocalizedString(@"errorMsg3", nil);
    }
    else if(![_confirmPWField.text isEqualToString:_newPWField.text])
    {
        errorMsg = NSLocalizedString(@"errorMsg5", nil);
    }
//    else if(![self isValidateEmail:_bdEmail.text])
//    {
//        errorMsg = MyLocal(@"errorMsg1",nil);
//    }
    
    else
    {
        NSRange range  = [_confirmPWField.text rangeOfString:@" "];
        //包含空格
        if (range.location != NSNotFound)
        {
            errorMsg = NSLocalizedString(@"password_illegal", nil);
        }
    }
    if(errorMsg)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:errorMsg activityAnimated:NO duration:1.5f];
        return;
    }

    
    NSMutableDictionary *parsDic = [NSMutableDictionary dictionaryWithCapacity:1];
//    [parsDic setValue:_oldPWField.text forKey:@"oldpass"];
    [parsDic setValue:_newPWField.text forKey:@"newpass"];
    [AppComManager getBanBuData:BanBu_Set_User_Password par:parsDic delegate:self];
    self.navigationController.view.userInteractionEnabled = NO;
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"changePWNotice", nil) activityAnimated:YES];
    
}

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.0];
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:1.5f];
        return;
    }
    //NSLog(@"res:%@",resDic);
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_Password])
    {
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            
            [UserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"isDefaultKey"];//用户用的是默认密码
            [UserDefaults setValue:_newPWField.text forKey:@"Pwd"];//新注册用户
            
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"changeOK", nil) activityAnimated:NO duration:1.5f];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        else
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.5f];
    }
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_confirmPWField resignFirstResponder];
    [_oldPWField resignFirstResponder];
    [_newPWField resignFirstResponder];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
//    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
//    if (section == 0) {
//        return 3;
//    }else{
//        return 1;
//    }
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//    if (section == 1) {
//        return MyLocal(@"为了您的帐号安全,请绑定您的邮箱地址", 绑定邮箱);
//    }
//    return nil;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.backgroundColor = [UIColor clearColor];
    if([ThemeManager getThemeImage:@"tablecell_backimage.png"])
        cell.backgroundColor = [UIColor colorWithPatternImage:[ThemeManager getThemeImage:@"tablecell_backimage.png"]];
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 180, 25)];
    textField.delegate = self;
    textField.tag = 111;
    textField.backgroundColor = [UIColor clearColor];
    textField.borderStyle = UITextBorderStyleNone;
    textField.clearsOnBeginEditing = YES;
    textField.textColor = [UIColor colorWithRed:50.0/255 green:79.0/255 blue:133.0/255 alpha:1.0];
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.returnKeyType = UIReturnKeyNext;
    textField.keyboardType = UIKeyboardTypeASCIICapable;
    textField.secureTextEntry = YES;
    [cell addSubview:textField];
    [textField release];
    if (indexPath.section == 0) {
        if(!indexPath.row)
        {
            cell.textLabel.text = NSLocalizedString(@"oldPWLabel", nil);
            _oldPWField = textField;
            CGFloat btnLen = [NSLocalizedString(@"oldPWLabel", nil) sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(150, 30)].width;
            _oldPWField.frame = CGRectMake(btnLen+30+5, 10, 270-btnLen, 25);
            textField.placeholder = NSLocalizedString(@"inputOldPW", nil);
            _oldPWField.text = [UserDefaults valueForKey:@"Pwd"];
            if([UserDefaults valueForKey:@"isDefaultKey"]&&[[UserDefaults valueForKey:@"isDefaultKey"] boolValue])
            {
                textField.text = [UserDefaults valueForKey:@"Pwd"];
            }
        }
        else if(indexPath.row == 1)
        {
            cell.textLabel.text = NSLocalizedString(@"newPWLabel", nil);
            _newPWField = textField;
            CGFloat btnLen = [NSLocalizedString(@"newPWLabel", nil) sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(150, 30)].width;
            _newPWField.frame = CGRectMake(btnLen+30, 10, 270-btnLen, 25);
            textField.placeholder =NSLocalizedString(@"errorMsg3", nil);
        }
        else if(indexPath.row == 2)
        {
            cell.textLabel.text = NSLocalizedString(@"confirmationLabel", nil);
            _confirmPWField = textField;
            CGFloat btnLen = [NSLocalizedString(@"confirmationLabel", nil) sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(150, 30)].width;
            _confirmPWField.frame = CGRectMake(btnLen+30+5, 10, 270-btnLen, 25);
            textField.placeholder =NSLocalizedString(@"cPlaceholedr", nil);
            textField.returnKeyType = UIReturnKeyGo;
        }
    }
//    else if (indexPath.section ==1)
//    {
//        _bdEmail = textField;
//        _bdEmail.secureTextEntry = NO;
//        _bdEmail.frame = CGRectMake(15, 10, 290, 25);
//        textField.placeholder =NSLocalizedString(@"errorMsg", nil);
//        textField.returnKeyType = UIReturnKeyGo;
//    }
    return cell;
}

-(BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    return [emailTest evaluateWithObject:email];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if(textField == _bdEmail)
    {
        return YES;
    }
    if (range.location>= 16)
        
        return NO;
    
    return YES;
    
}
#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if(textField.returnKeyType == UIReturnKeyNext)
    {
        UITableViewCell *cell = (UITableViewCell *)textField.superview;
        
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        indexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
        UITextField *inputField = (UITextField *)[[self.tableView cellForRowAtIndexPath:indexPath] viewWithTag:111];
        [inputField becomeFirstResponder];
    }
    else
    {
        [self performSelector:@selector(complete:) withObject:nil];
    }
    
    return  YES;
}



@end
